'''backtest
start: 2019-01-01 00:00:00
end: 2021-04-24 00:00:00
period: 90m
basePeriod: 90m
exchanges: [{"eid":"Futures_OKCoin","currency":"BTC_USDT","balance":200000,"stocks":0}]
'''
# basePeriod 回测时设置的底层K线周期

# 导入库
import talib as TA
import numpy as np
import math
import urllib3
import json
from datetime import datetime

# 策略参数
contract_type = "this_week" #合约类型，交割合约一般有 this_week, next_week, quarter, next_quarter，永续合约一般有swap
margin_level = 10 #杠杆倍数
want_profit = 0.01 #想要的额外收入(+汇率损失)
ignore_range = 0.001 #例如USDT对USD, 对冲期的安全波动范围，策略会忽略这个范围的波动
max_wait_order = 10000 #订单处理最长等待时间（毫秒）
wait_ms = 3000 #默认等待毫秒
traders_recorder = False #是否记录所有交易

handfee={'OKEX':0.001, 'Futures_OKCoin':0.001}#手续费
trade_amount={'ETH_USD':0.5, 'BCH_USD':0.5, 'BTC_USD':0.05}#每次交易数量 例如0.5个bch
contract_min={'ETH_USD':10,	'BCH_USD':10, 'BTC_USD':100}#一合约价值多少美金 USD,用这个计算买入张数

price_n = {'ETH_USDT': 4, 'ETH_USD':3, 'BCH_USDT': 4, 'BCH_USD':3, 'BTC_USDT': 4, 'BTC_USD':2} # 价格精度
num_n = {'ETH_USDT': 3, 'ETH_USD':0, 'BCH_USDT': 3, 'BCH_USD':0, 'BTC_USDT': 3, 'BTC_USD':0} # 数量精度
# 最小买入量
minestbuy={'ETH_USDT':0.001, 'ETH_USD':1, 'BCH_USDT':0.001,	'BCH_USD':1, 'BTC_USDT':0.001, 'BTC_USD':1}
# 定价单调整价格的单位(每次调整万1, 大致等于25分钟调整1%)
price_step	={'ETH_USDT':0.03, 'ETH_USD':0.03, 'BCH_USDT':0.05, 'BCH_USD':0.05,	'BTC_USDT':0.65, 'BTC_USD':0.65}


class ExchangProcessor:
    def __init__(self, exA, exB):
        _CDelay(wait_ms)
        self.exA = exA
        self.exB = exB
        self.pre_time = datetime.now()

    # 处理交易
    def work(self, exA, exB):
        cur_time = datetime.now()
        global hedging_op, pending_pos, hedging_complete
        passedtime = cur_time - self.pre_time
        self.pre_time = cur_time

        USDT_r = getUSDTratio()

        # get information
        A_account = _C(exA.GetAccount)
        A_exname = exA.GetName()
        A_currency = exA.GetCurrency()
        A_quotecurrency = exA.GetQuoteCurrency()  # 返回交易所操作的基础货币名称。例如，BTC_CNY就返回CNY，ETH_BTC就返回BTC
        A_ticker = _C(exA.GetTicker)
        A_last = A_ticker['Last']
        A_last_fixed = A_last * USDT_r  # Fixed price: ETH / USD
        A_depth = _C(exA.GetDepth)  # 返回市场深度单数据结构中Bids、Asks数组中的元素的数据结构
        A_orders = _C(exA.GetOrders)  # 获取所有未完成的订单。返回值：Order结构体数组, Futures_Bibox 不支持
        A_buy1 = A_depth['Bids'][0]['Price']
        A_sell1 = A_depth['Asks'][0]['Price']

        exB.SetContractType(contract_type)  # 设置合约类型
        exB.SetMarginLevel(margin_level)  # 设置杆杠大小
        B_account = _C(exB.GetAccount)
        B_exname = exB.GetName()  # 返回交易所名称
        B_currency = exB.GetCurrency()
        B_quotecurrency = exB.GetQuoteCurrency()  # 返回交易所操作的货币对名称。数字货币交易所返回字符串，例如LTC_BTC
        B_ticker = _C(exB.GetTicker)
        B_last = B_ticker['Last']  # 最后成交价
        B_depth = _C(exB.GetDepth)
        B_orders = _C(exB.GetOrders)
        B_buy1 = B_depth['Bids'][0]['Price']
        B_sell1 = B_depth['Asks'][0]['Price']
        cdiff = abs(B_last - A_last_fixed) / A_last_fixed
        cdiff2 = (B_last - A_last_fixed) / A_last_fixed
        target_bofu = want_profit + handfee[A_exname] * 2 + handfee[B_exname] * 2 + ignore_range

        # 开始对冲
        if len(limit_orders) == 0 and cdiff > target_bofu:
            hedging_op += 1
            # 合约份数
            heyuefenshu_B = _N(trade_amount[B_currency] * B_last / contract_min[B_currency], 0)
            exact_amount = heyuefenshu_B * contract_min[B_currency] / B_last

            if A_last_fixed > B_last:
                if A_account['Balance'] * 0.9 > exact_amount * A_last and B_account['Stocks'] * 0.9 > exact_amount:
                    global hedging_real
                    hedging_real += 1

                    # 从A交易所买一个币
                    force_limited_order("sell", exA, A_buy1, exact_amount, "spot")
                    # 在B交易所卖出
                    exB.SetDirection("buy")
                    force_limited_order("buy", exB, B_sell1, heyuefenshu_B, "futures")

                    posA = {'type': 'spot-sell',
                            'exchange': exA,
                            'price': A_buy1,
                            'amount': exact_amount,
                            'starttime': get_ChinaTimeString()}
                    pending_pos.append(posA)

                    posB = {'type': 'futures-buyup',
                            'exchange': exB,
                            'price': B_sell1,
                            'amount': heyuefenshu_B,
                            'starttime': get_ChinaTimeString()}
                    pending_pos.append(posB)
            else:
                if A_account['Balance'] * 0.9 > exact_amount * A_last and B_account['Stocks'] * 0.9 > exact_amount:
                    global hedging_real
                    hedging_real += 1

                    force_limited_order("buy", exA, A_sell1, exact_amount, "spot")
                    force_limited_order("buy", exB, B_sell1, heyuefenshu_B, "futures")

                    posA = {'type': 'spot-bu',
                            'exchange': exA,
                            'price': A_sell1,
                            'amount': exact_amount,
                            'starttime': get_ChinaTimeString()}
                    pending_pos.append(posA)

                    posB = {'type': 'futures-buydown',
                            'exchange': exB,
                            'price': B_sell1,
                            'amount': heyuefenshu_B,
                            'starttime': get_ChinaTimeString()}
                    pending_pos.append(posB)

        #   结束对冲
        if len(limit_orders) == 0 and cdiff <= ignore_range and A_orders['length'] == 0 and B_orders[
            'length'] == 0 and len(pending_pos) > 0:
            hedging_complete += 1
            for posinfo in pending_pos:
                ticker = _C(posinfo['exchange'].GetTicker)
                last = ticker['Last']
                depth = _C(posinfo['exchange'].GetDepth)
                buy1 = depth['Bids'][0]['Price']
                sell1 = depth['Asks'][0]['Price']
                account = _C(posinfo['exchange'].GetAccount)

                if posinfo['type'] == 'futures-buydown':
                    posinfo['exchange'].SetDirection("closesell")
                    force_limited_order("sell", posinfo['exchange'], buy1, posinfo['amount'], "futures")
                if posinfo['type'] == 'futures-buyup':
                    posinfo['exchange'].SetDirection("closebuy")
                    force_limited_order("sell", posinfo['exchange'], buy1, posinfo['amount'], "futures")
                if posinfo['type'] == 'spot-buy':
                    force_limited_order("sell", posinfo['exchange'], buy1, min(account['Stocks'], posinfo['amount']),
                                        "spot")
                if posinfo['type'] == 'spot-sell':
                    force_limited_order("buy", posinfo['exchange'], sell1,
                                        min(account['Balance'] / last, posinfo['amount']), "spot")
            pending_pos = []

        #     自动释放对冲仓位
        B_position = _C(exB.GetPosition)
        if B_position.length == 0 and len(pending_pos) > 0 and len(limit_orders) == 0 and len(A_orders) == 0 and len(
                B_orders) == 0:
            Log('检测到Okex的仓位已被强平，执行自动释放对冲仓位。')
            hedging_complete += 1
            for posinfo in pending_pos:
                ticker = _C(posinfo['exchange'].GetTicker)
                last = ticker['Last']
                depth = _C(posinfo['exchange'].GetDepth)
                buy1 = depth['Bids'][0]['Price']
                sell1 = depth['Asks'][0]['Price']
                account = _C(posinfo['exchange'].GetAccount)

                if posinfo['type'] == 'spot-buy':
                    force_limited_order("sell", posinfo['exchange'], buy1, min(account['Stocks'], posinfo['amount']),
                                        "spot")
                if posinfo['type'] == 'spot-sell':
                    force_limited_order("buy", posinfo['exchange'], sell1,
                                        min(account['Balance'] / last, posinfo['amount']), "spot")
            pending_pos = []

        # # 状态
        # table1 = {'type': 'table', 'title': '交易所', 'cols': ['交易所', '交易对', '最新价格', '钱', '币', '未完成订单', '买一', '卖一'], 'rows': []}
        # table2 = {'type': 'table', 'title': '统计', 'cols': ['轮询时间', '当前价差', '目标价差', '对冲机会/实际对冲次数/对冲完成次数', 'USDT/USD', '忽略波动范围'],
        #           'rows': []}
        # table3 = {'type': 'table', 'title': '未完成对冲仓位', 'cols': ['交易所', '类型', '价格', '数量', '开仓时间'], 'rows': []}
        # table4 = {'type': 'table', 'title': '未完成定价单', 'cols': ['交易所', '订单ID', '发单日期'], 'rows': []}
        # table5 = {'type': 'table', 'title': '交易历史', 'cols': ['交易所', '日期', '类型', '成交数量', '发单数量', '成交价', '发单价', '备注'], 'rows': []}
        # table6 = {'type': 'table', 'title': '期货仓位', 'cols': ['交易所', '持仓量', '冻结量', '持仓均价', '实现盈余', '类型', '合约代码'], 'rows': []}
        #
        # table1['rows'].append([A_exname, A_currency, A_last + '(修正价:' + A_last_fixed + ')', A_account['Balance'], A_account['Stocks'],
        #                   len(A_orders), A_depth['Bids'][0]['Price'], A_depth['Asks'][0]['Price']])
        #
        # table1['rows'].append([B_exname, B_currency, B_last, B_account['Balance'], B_account['Stocks'], len(B_orders),
        #                        B_depth['Bids'][0]['Price'], B_depth['Asks'][0]['Price']])
        #
        # table2['rows'].append(
        #     [passedtime + '毫秒', cdiff2, target_bofu, hedging_op + '/' + hedging_real + '/' + hedging_complete, USDT_r,
        #      ignore_range])
        #
        # for ( thidx=0; thidx < pending_pos.length; ++thidx){
        #      posinfo=pending_pos[thidx]
        # table3['rows'].append([posinfo.exchange.GetName(), posinfo.type, posinfo['Price'], posinfo.amount, posinfo.starttime])
        # }
        # for ( idx2=0; idx2 < limit_orders.length; ++idx2){
        #      info=limit_orders[idx2]
        # table4['rows'].append([info.exchange.GetName(), info.ID, info.utcdate])
        # }
        # for ( i=0; i < trades.length; i++){
        #     table5['rows'].append([trades[i].exname, trades[i].time, trades[i].type, trades[i].RealAmount, trades[i].WantAmount,
        #                       trades[i].RealPrice, trades[i].WantPrice, trades[i].Memo])
        # }
        # for ( i=0; i < B_position.length; i++){
        #     table6['rows'].append(
        #         [B_exname, B_position[i].Amount, B_position[i].FrozenAmount, B_position[i]['Price'], B_position[i].Profit,
        #          B_position[i].Type, B_position[i].ContractType])
        # }
        #
        # logstatus = ('`' + JSON.stringify([table1, table2, table3, table4, table6, table5]) + '`' + '\n')
        stocksbalance = A_account['Stocks'] + B_account['Stocks']



# 全局状态变量
# ==============================================================================================================================
pre_time = 0 #记录轮询间隔时间
limit_orders = [] #限价单
trades = [] #所有交易
pending_pos = [] #未完成对冲仓位
hedging_op = 0 #对冲机会
hedging_real = 0 #真实对冲次数
hedging_complete = 0 #对冲完成次数
# ==============================================================================================================================

# 程序主函数
def onTick():
    # Log(exchange.GetTicker())
    bar = _C(exchange.GetRecords)  # 获取K线数组
    if len(bar) < 100:  # 如果K线数组长度太小，就直接返回跳过
        return

    atr = TA.ATR(bar, 30)
    ma1 = TA.MA(bar, 250)
    top, mid1, bottom = TA.BOLL(bar, 26, 2)

    # 短周期MACD
    stmacd = TA.MACD(bar, 12, 26, 100)  # 计算MACD值
    macd = stmacd[2]
    prev_macd = macd[-1]

    # 长周期MACD
    ltmacd = TA.MACD(bar, 12 * k, 26 * k, 100)
    macd2 = ltmacd[2]
    prev_macd2 = macd2[-1]

    rsi1 = TA.RSI(bar, 26)
    latest_rsi1 = rsi1[-1]

    lc = bar[-1]['Close']  # 获取最新价格（卖价）

    # 技术指标空变量处理
    if prev_macd is None:
        prev_macd = 0
    if prev_macd2 is None:
        prev_macd2 = 0
    if macd[-6] is None:
        macd[-6] = 0
    if macd2[-6] is None:
        macd2[-6] = 0
    if atr[-1] is None:
        atr[-1] = 0
    if latest_rsi1 is None:
        latest_rsi1 = 0

    lots = math.ceil(lossmoney / (atr[-1] * bigPointValue * contractUnit))

    pos = _C(exchange.GetPosition)  # 现货交易所不能用此语句

    ############################ 建仓逻辑 #########################################
    # 若当前空仓，进入判断逻辑
    # Log(pos)
    myac = _C(exchange.GetAccount)
    if len(pos) == 0:
        myprice = bar[-1]['Open']  # 取最新开盘价
        if prev_macd > 0 and lc > ma1[-1] and lc > top[-1] and prev_macd > macd[-6] and prev_macd2 > macd2[
            -6] and latest_rsi1 > (50 + p):
            Log('开多单，下单合约数为：', lots)
            exchange.SetDirection("buy")  # 设置交易方向和类型
            exchange.Buy(myprice, lots)  # 开多单
            Sleep(LoopInterval * 6000)
            Log("等待时间过后，持仓量:", len(_C(exchange.GetPosition)), "余额：", myac['Balance'], "冻结余额：", myac['FrozenBalance'],
                "合约当前可用保证金：", myac["Stocks"], "冻结的BTC/LTC数量：", myac["FrozenStocks"])

        elif prev_macd < 0 and lc < ma1[-1] and lc < bottom[-1] and prev_macd < macd[-6] and prev_macd2 < macd2[
            -6] and latest_rsi1 < (50 - p):
            Log('开空单，下单合约数为：', lots)
            exchange.SetDirection("sell")  # 设置交易方向和类型
            exchange.Sell(myprice, lots)  # 开空单
            Sleep(LoopInterval * 6000)
            Log("等待时间过后，持仓量:", len(_C(exchange.GetPosition)), "余额：", myac['Balance'], "冻结余额：", myac['FrozenBalance'],
                "合约当前可用保证金：", myac["Stocks"], "冻结的BTC/LTC数量：", myac["FrozenStocks"])

    ############################ 平仓逻辑 #########################################
    pos = _C(exchange.GetPosition)
    myac = _C(exchange.GetAccount)
    if len(pos) > 0:
        higherAfterEntry = max(bar[-1]['Open'], bar[-1]['High'])
        lowerAfterEntry = min(bar[-1]['Open'], bar[-1]['Low'])
        # 多仓
        if pos[0]['Type'] == PD_LONG:
            # Log('多头')
            if prev_macd < macd[-6] and lc < higherAfterEntry * (100 - a) / 100:
                Log("平多仓前-仓位类型:", _C(exchange.GetPosition)[0]['Type'], "可用资金：", myac['Balance'])
                exchange.SetDirection("closebuy")
                id = exchange.Sell(bar[-1]['Open'] - minimove * pricescale, pos[0]['Amount'])
                Sleep(LoopInterval * 6000)
                # 当订单有效，才有有效的id返回
                if id is not None:
                    order = _C(exchange.GetOrder, id)
                    # 若订单状态尚未完成，不应该有进一步的平仓、开仓操作
                    if order['Status'] != ORDER_STATE_CLOSED:  # 订单状态尚未完成
                        Log('平空订单未完成，等待下一个bar的处理')
                        return
                    Log("可用资金:", myac['Balance'])

        # 空
        elif pos[0]['Type'] == PD_SHORT:
            # Log('空头平仓')
            if prev_macd > macd[-6] and lc > lowerAfterEntry * (100 + a) / 100:
                Log("平空仓前-仓位类型:", _C(exchange.GetPosition)[0]['Type'], "可用资金：", myac['Balance'])
                exchange.SetDirection("closesell")
                id = exchange.Buy(bar[-1]['Open'] + minimove * pricescale, pos[0]['Amount'])
                Sleep(LoopInterval * 6000)
                # 当订单有效，才有有效的id返回
                if id is not None:
                    order = _C(exchange.GetOrder, id)
                    # 若订单状态尚未完成，不应该有进一步的平仓、开仓操作
                    if order['Status'] != ORDER_STATE_CLOSED:  # 订单状态尚未完成
                        Log('平空订单未完成，等待下一个bar的处理')
                        return
                    Log("可用资金:", myac['Balance'])

# 从Coincap获取USDT汇率
def getUSDTratio():
    coin_url = 'https://api.coincap.io/v2/assets/ethereum/'
    http = urllib3.PoolManager()
    response = http.request('GET', coin_url)
    resp_dict = response.data.decode('utf-8')
    return float(resp_dict['data']['priceUsd'])


# 获得中国时间，等其他函数处理后再继续
def get_ChinaTimeString():
    return datetime.now().strftime("%Y/%m/%d %H:%M:%S")


# 处理定价单
def process_limiteorders(limit_orders: list):
    limit_orders_new = []
    cur_time = datetime.now()
    for lo in limit_orders:
        create_time = lo.create_time
        passedtime = cur_time-create_time #两个Date相减的差是毫秒数

        if passedtime > max_wait_order:
            exchange_c = lo.exchange
            order_ID = lo.ID
            ordermode = lo.mode
            exname = exchange_c.GetName()
            account = _C(exchange_c.GetAccount)
            ticker = _C(exchange_c.GetTicker)
            last = ticker["Last"]
            orderdata = _C(exchange_c.GetOrder, order_ID)
            type = orderdata["Type"]
            currency = exchange_c.GetCurrency()
            # 若订单并非已经完成
            if orderdata["Status"] != ORDER_STATE_CLOSED:
                notcompleted = orderdata["Amount"] - orderdata["DealAmount"]
                exchange_c.CancelOrder(order_ID)
                # 若是买单
                if type==ORDER_TYPE_BUY:
                    allowbuy = notcompleted
                    if allowbuy >= minestbuy[currency]:
                        limited_order_ID=retryBuy(exchange_c, orderdata["Price"] + price_step[currency], allowbuy, ordermode)
                        Log("加价买入。" + orderdata["Price"] + "|" + (orderdata["Price"] + price_step[currency]))
                        limited_order_data = {'exchange': exchange_c, 'ID': limited_order_ID, 'create_time': datetime.now(),
                                              'utcdate': get_ChinaTimeString, 'mode': ordermode}
                        limit_orders_new.append(limited_order_data)
                elif type==ORDER_TYPE_SELL: # 若是卖单
                    allowsell = notcompleted
                    if allowsell >= minestbuy[currency]:
                        limited_order_ID=retrySell(exchange_c, orderdata["Price"] + price_step[currency], allowsell, ordermode)
                        Log("降价卖出。" + orderdata["Price"] + "|" + (orderdata["Price"] - price_step[currency]))
                        limited_order_data = {'exchange': exchange_c, 'ID': limited_order_ID, 'create_time': datetime.now(),
                                              'utcdate': get_ChinaTimeString, 'mode': ordermode}
                        limit_orders_new.append(limited_order_data)

                # 保存交易信息
                if type===ORDER_TYPE_BUY:
                    details = {'type': '限价买', 'time': lo.utcdate, 'RealAmount': orderdata['DealAmount'], 'WantAmount': orderdata['Amount'],
                               'RealPrice': orderdata['Price'], 'WantPrice': orderdata['Price'], 'Memo': '部分完成',
                               'exname': exname}
                    if traders_recorder:
                        trades.append(details)
                elif type==ORDER_TYPE_SELL:
                    details = {'type': '限价卖', 'time': lo.utcdate, 'RealAmount': orderdata['DealAmount'],
                               'WantAmount': orderdata['Amount'],
                               'RealPrice': orderdata['Price'], 'WantPrice': orderdata['Price'], 'Memo': '部分完成',
                               'exname': exname}
                    if traders_recorder:
                        trades.append(details)
            else:
                if type==ORDER_TYPE_BUY:
                    details = {'type': '限价买', 'time': lo.utcdate, 'RealAmount': orderdata['DealAmount'],
                               'WantAmount': orderdata['Amount'],
                               'RealPrice': orderdata['Price'], 'WantPrice': orderdata['Price'], 'Memo': '已完成',
                               'exname': exname}
                    if traders_recorder:
                        trades.append(details)
                elif type==ORDER_TYPE_SELL:
                    details = {'type': '限价卖', 'time': lo.utcdate, 'RealAmount': orderdata['DealAmount'],
                               'WantAmount': orderdata['Amount'],
                               'RealPrice': orderdata['Price'], 'WantPrice': orderdata['Price'], 'Memo': '已完成',
                               'exname': exname}
                    if traders_recorder:
                        trades.append(details)

        else:
            limit_orders_new.append(lo)
    limit_orders = limit_orders_new


# 强制执行限价单
def force_limited_order(type, ex, price, num, mode):
    if type=='buy':
        id = retryBuy(ex, price, num, mode)
    else:
        id = retrySell(ex, price, num, mode)
    order1 = {'exchange': ex, 'ID': id, 'create_time': datetime.now(), 'utcdate': get_ChinaTimeString(),
              'mode': mode}
    limit_orders.append(order1)

    while len(limit_orders)!=0:
        process_limiteorders(limit_orders)
        Sleep(wait_ms)


# 重试购买，直到成功返回
def retryBuy(ex, price, num, mode):
    currency = ex.GetCurrency()
    bid = ex.Buy(_N(price, price_n[currency]), _N(num, num_n[currency]))  # 开多单
    while bid < 1 or bid is None:
        Log("Buy失败，正在重试。")
        Sleep(wait_ms)
        if mode=='spot':
            account = ex.GetAccount()
            ticker = ex.GetTicker()
            last = ticker["Last"]
            fixedAmount = min(account['Balance']*0.95/last, num)
            bid = ex.Buy(_N(price, price_n[currency]), _N(fixedAmount, num_n[currency]))  # 开多单
        elif mode=='futures':
            if num==0:
                break
            bid = ex.Buy(_N(price, price_n[currency]), _N(num, num_n[currency]))  # 开多单

    return bid


# 重试卖出，直到成功返回
def retrySell(ex, price, num, mode):
    currency = ex.GetCurrency()
    bid = ex.Sell(_N(price, price_n[currency]), _N(num, num_n[currency]))  # 开多单
    while bid < 1 or bid is None:
        Log("Sell失败，正在重试。")
        Sleep(wait_ms)
        if mode=='spot':
            account = ex.GetAccount()
            ticker = ex.GetTicker()
            last = ticker["Last"]
            fixedAmount = min(account['Balance']*0.95/last, num)
            bid = ex.Sell(_N(price, price_n[currency]), _N(fixedAmount, num_n[currency]))  # 开多单
        elif mode=='futures':
            if num==0:
                break
            bid = ex.Sell(_N(price, price_n[currency]), _N(num, num_n[currency]))  # 开多单

    return bid


def init_obj():
    _CDelay(wait_ms)
    global pre_time
    pre_time = datetime.now()





def main():
    # exchanges:FMZ储存如同exchange交易所对象的所有交易所对象的数组，可能包含多个交易所对象，exchanges[0]即是exchange
    for i in range(len(exchanges)):

    pre_profit = _G("pre_profit")
    Log('之前收入累计：' + pre_profit)
    lastprofit=-1
    total_loop=0
    beginrunning = get_ChinaTimeString()

    while True:
        total_loop+=1
        allstatus = ''
        allstatus += ('策略启动时间: ' + beginrunning + '#0000ff\n')
        mybalance = 0



    # _C(exchange.SetContractType, 'quarter')	# 币安季度合约
    # _C(exchange.SetContractType, 'next_quarter')	# 币安次季合约
    global lc
    Instruments = 'BTC_USDT'
    myac = _C(exchange.GetAccount)
    # Log("资产信息:", myac['Balance'])
    # exchange.SetMarginLevel(marginlevel) # 具体支持的杠杆大小查看相应的交易所
    # try except 只能用于实盘/模拟盘，不能用于回测。取消注释时注意其包含的while True部分的代码缩进也要改动
    # try:
    while True:  # 返回true证明与CTP服务器行情与数据的两台服务器都连接正常
        _C(exchange.SetContractType, 'swap')
        # Log(_C(exchange.GetRecords))
        onTick()

        # except Exception as e:
        # print (e)
        Sleep(LoopInterval * 1000)  # Sleep(1000)为休眠一秒,商品期货的策略可以不写Sleep()函数
        # orders = _C(exchange.GetOrders)
        # if len(orders) > 0 :
        #  for i in range(0, len(orders)):
        #    if orders[i]['Status'] == ORDER_STATE_PENDING:
        #      Log("未完成订单一的信息,ID:", orders[i]["Id"], "Price:", orders[i]["Price"], "Amount:", orders[i]["Amount"], "DealAmount:", orders[i]["DealAmount"], "type:", orders[i]["Type"])
        #    exchange.CancelOrder(orders[i]["Id"])